package com.robot.service.impl;

import com.aliyun.sdk.service.dysmsapi20170525.models.SendSmsResponse;
import com.robot.common.enums.ResponseEnum;
import com.robot.common.exception.BusinessException;
import com.robot.common.utils.AliSmsUtils;
import com.robot.common.utils.CaptchaCacheWithGuava;
import com.robot.common.utils.PhoneNumberValidator;
import com.robot.common.utils.VerificationCodeUtils;
import com.robot.service.SmsService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutionException;

@Service
@Slf4j
public class SmsServiceImpl implements SmsService {

    @Autowired
    private AliSmsUtils aliSmsUtils;



    @Override
    public String sendSmsMessage(String userPhone) throws ExecutionException, InterruptedException {
        String mes="";
        //校验手机号格式是否正确
        if (!PhoneNumberValidator.isValidPhoneNumber(userPhone)) {
            throw new BusinessException(ResponseEnum.ILLEGAL_PARAMETER.getCode(), "手机号格式错误！");
        }
        try{
            //根据手机号生成短信验证码
            String code = VerificationCodeUtils.generateCustomVerificationCode();
            log.info("验证码。。。。。。。。。。。。。{}",code);
            //将验证码放入内存缓存，并设置5分钟的过期时间
            CaptchaCacheWithGuava.putCaptcha(userPhone,code);

            //调用发送短信接口
            SendSmsResponse sendSmsResponse= aliSmsUtils.sendSms(userPhone,code);
            mes=sendSmsResponse.getBody().getMessage();
        }catch (Exception e){
            throw new BusinessException(ResponseEnum.ILLEGAL_PARAMETER.getCode(), "发送验证码失败！");
        }
        return  mes;
    }
}
